<?php
/**
 * @package PWE.controler
 * @author Gmax <gmaxfr78@gmail.com>
 * description : gestion des requetes ajax
 */
class ajax extends controler{
    /**
     * rooter d'appel ajax
     * @return json
     */
    public static function getAjax(){
        $action = str_replace('.ajax', '', navigation::getTargetName());
        $query = navigation::getQuery();
        $return = array('success'=>false, 'datas'=>'erreur');
        if(file_exists(PWE::getThemePath().'/modules/ajax.class.php')){
            include_once (PWE::getThemePath().'/modules/ajax.class.php');
        }
        if(method_exists('modules_ajax', $action)){
            $return = call_user_func_array('\modules_ajax::'.$action, array($query['data']));
        }elseif(method_exists('ajax', $action)){
            $return = call_user_func_array('\ajax::'.$action, array($query['data']));
        }else{
            $return['datas'] = 'class ou methode introuvable';
        }
        return self::outputFormat($return);
    }
    /**
    * retourne un objet de reponse json
    * @param array $datas
    * @return json
    */
    public static function outputFormat($datas){
        return json_encode($datas);
    }
    /**
     * verification de la base : connectibilité, existance, existance des tables, prefix de table
     * @param array $datas [server,username,password,database_name,database_prefix]
     * @return array
     */
    public static function checkDataBase($datas){
        $returnDatas = array(
            'server_connexion'=>array('success'=>false,'msg'=>'not attempt'),
            'database_connexion'=>array('success'=>false,'msg'=>'not attempt'),
            'table_connexion'=>array('success'=>false,'msg'=>'not attempt')
        );
        
        $connexion = bdd_sql::testConnexion($datas['server'], $datas['username'], $datas['password'],$datas['database_name']);
        $returnDatas['server_connexion']['msg'] = $connexion['msg'];
        $returnDatas['server_connexion']['success'] = $connexion['success'];
        if($connexion['success']){ // si la connexion existe
            //tester base de données
            if($connexion['pdo']){ //en mode PDO
                try{
                    $connexion['connect'] = new PDO('mysql:host='.$datas['server'].';dbname='.$datas['database_name'].';charset=UTF8', $datas['username'], $datas['password']);
                    $returnDatas['database_connexion']['msg'] = 'Connexion à la base de données établie';
                    $returnDatas['database_connexion']['success'] = true;
                }catch (PDOException $e) {
                    $returnDatas['database_connexion']['msg'] = 'Connexion à la base de données impossible';
                    $returnDatas['database_connexion']['success'] = false;
                }
            }else{ // en mode mysql
                if(mysql_select_db($datas['database_name'], $connexion['connect'])){
                    $returnDatas['database_connexion']['msg'] = 'Connexion à la base de données établie';
                    $returnDatas['database_connexion']['success'] = true;
                }else{
                    $returnDatas['database_connexion']['msg'] = 'Connexion à la base de données impossible';
                    $returnDatas['database_connexion']['success'] = false;
                }
            }
            
            // test des tables -> tester l'existance de la table user et de l'entrée 1 pour l'admin de base
            if($returnDatas['database_connexion']['success']){
                $sql = 'SELECT * FROM '.$datas['database_prefix'].'user WHERE id=1';
                if($connexion['pdo']){ //en mode PDO
                    try{
                        $result = $connexion['connect']->query($sql);
                        if($result && $result->rowCount()===1){
                            $returnDatas['table_connexion']['msg'] = 'La base de données est correctement installée';
                            $returnDatas['table_connexion']['success'] = true;
                        }else{
                            $returnDatas['table_connexion']['msg'] = 'La base de données n\'est pas installée';
                            $returnDatas['table_connexion']['success'] = false;
                        }
                    }catch(PDOException $e){
                         $returnDatas['table_connexion']['msg'] = $e->getMessage();
                         $returnDatas['table_connexion']['success'] = false;
                    }
                }else{ // en mode mysql
                    $result = @mysql_query($sql,$connexion['connect']);
                    if(@mysql_affected_rows($connexion['connect'])===1){
                        $returnDatas['table_connexion']['msg'] = 'La base de données est correctement installée';
                        $returnDatas['table_connexion']['success'] = true;
                    }else{
                        $returnDatas['table_connexion']['msg'] = 'La base de données n\'est pas installée';
                        $returnDatas['table_connexion']['success'] = false;
                    }
                }
            }
        }
        $retour = array('success'=>true,'connect'=>$connexion['success'],'datas'=>$returnDatas);
        
        return $retour;
    }
    /**
     * upload de fichier asynchrone
     * @param array $datas
     * @return array
     */
    public static function uploadFile($datas){
        $uploadControler = null;
        $retour = array('success'=>true,'datas'=>array());
        $datas = array(
            'filename'=>'',
            'path'=>'',
            'url'=>''
        );
        $retour['datas'] = $datas;
        
        return $retour;
    }
    
    public static function AutoCompletionVilleCp($datas){
        $retour = array('success'=>true,'datas'=>array());
        
        $query = 'SELECT id,nom,cp,lat,lng FROM '.PWE::getPrefixBdd().'ville WHERE ';
        if(isset($datas['ville'])&&$datas['ville']!==''){
            $query .= 'nom LIKE "'.$datas['ville'].'%" ';
        }elseif(isset($datas['cp'])&&$datas['cp']!==''){
            $query .= 'cp LIKE "'.$datas['cp'].'%" ';
        }else{
            $query = '';
        }
        
        $return = array();
        if($query!==''){
            if(isset($datas['maxRows'])&&$datas['maxRows']>0){
                $query .= 'LIMIT 0,'.$datas['maxRows'];
            }
            
            $results = bdd_sql::doSql($query,true,true);
            if($results['count']>0){
                foreach($results['results'] as $result){
                    $datas = array(
                        'id'=>$result['id']
                        ,'ville'=>$result['nom']
                        ,'cp'=>$result['cp']
                        ,'lat'=>$result['lat']
                        ,'lng'=>$result['lng']
                    );
                    $return[] = $datas;
                }
                $retour['datas'] = $return;
            }            
        }
        return $retour;
    }
}
?>